import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Classify from '../views/Classify.vue'
import Study from '../views/Study.vue'
import My from '../views/My.vue'
import Menu from '../components/Menu.vue'
import Recommend from '../views/Home/Recommend.vue'
import Course from '../views/Home/Course.vue'
import Tiny from '../views/Home/Tiny.vue'
import Details from '../views/Details.vue'
import Datum from '../views/My/Datum.vue'
import Car from '../views/My/Car.vue'
import Order from '../views/My/Order.vue'
import Login from '../views/Login.vue'
import Reigist from '../views/Reigist.vue'
import store from '../store/index'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    components: { default: Home, Menu },
    children: [
      {
        path: '/',
        component: Recommend
      },
      {
        path: '/course',
        component: Course
      },
      {
        path: '/tiny',
        component: Tiny
      }
    ]
  },
  {
    path: '/classify',
    name: 'Classify',
    components: { default: Classify, Menu }
  },
  {
    path: '/study',
    name: 'Study',
    components: { default: Study, Menu },
    meta: {
      isNeed: true
    }
  },
  {
    path: '/my',
    components: { default: My, Menu },
  },
  {
    path: '/details/:id',
    name: 'Details',
    components: { default: Details }
  },
  {
    path: '/datum',
    component: Datum,
    meta: {
      isNeed: true
    }
  },
  {
    path: '/car',
    component: Car,
    meta: {
      isNeed: true
    }
  },
  {
    path: '/order',
    component: Order,
    meta: {
      isNeed: true
    }
  },
  {
    path: '/login',
    component: Login,
    beforeEnter: (to, from, next) => {
      if (store.state.user.userid) {
        next('/');
      }else{
        next()
      }
      
    }
  },
  {
    path: '/reigist',
    component: Reigist
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
router.beforeEach((to, from, next) => {
  if (to.meta.isNeed) {  // 判断该路由是否需要登录权限
    if (store.state.user.userid) {  // 通过vuex state获取当前的token是否存在
      next();
    }
    else {
      next({
        path: '/login',
        query: { redirect: to.fullPath }  // 将跳转的路由path作为参数，登录成功后跳转到该路由
      })
    }
  }
  else {
    next();
  }
})
export default router
